package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.NormalTableAdapter;
import com.yxt.common.ui.NormalTableAdapter.TableCell;
import com.yxt.common.ui.NormalTableAdapter.TableRow;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Favirote;
import com.yxt.model.Station;
import com.yxt.service.FavoriteService;
import com.yxt.service.StationService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.LinearLayout.LayoutParams;

/**
 * 测站列表
 * @author Crazyman
 */
public class StationListActivity extends Activity {
	private int cols = 2;
	private int itemHeight = 70;
	private int tabHeight = 40;
	private int color = Color.WHITE;
	private static final int MENU_SEARCH = Menu.FIRST + 1;
	private static final int MENU_DOWNLOAD = Menu.FIRST + 2;
	private StationService service = new StationService(StationListActivity.this);
	private ProgressDialog dialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.station_list); // 软件activity的布局
		ActivityStackControlUtil.add(this);
		initComponent();
	}
	
	private void initComponent() {
		Button btnBackHome = (Button) findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				//btnBackHome.setBackgroundResource(5);
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		fillStationList();
	}
	
	private void downloadStationList() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new StationHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}
	}
	

	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		String itemId = intent.getStringExtra("itemId");
		Map<String, String> menu = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get(itemId);
		String server = menu.get("server");
		CommConstant.Sever.RAIN_SERVER = server;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"locations.xml");
		} else {
			URL url = new URL(server + "search/Search.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&key=&scope=1");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class StationHandler extends DefaultHandler {		
		public void endDocument() throws SAXException {
			super.endDocument();
		}

		public void startDocument() throws SAXException {
			super.startDocument();
			service.deleteStation();
		}

		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("info".equals(localName)) {
				Station station = new Station();
				station.setCode(attrs.getValue("code"));
				station.setName(attrs.getValue("name"));
				station.setAddr(attrs.getValue("addr"));
				station.setType(attrs.getValue("type"));
				service.saveStation(station);		
			} else if ("message".equals(localName)) {
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}

	private void fillStationList() {
		List<TableRow> table = new ArrayList<TableRow>();
		int[] width = { 250, 50 };

		TableCell[] header = new TableCell[1];
		header[0] = new TableCell("热点搜藏", LayoutParams.FILL_PARENT, tabHeight,
				Color.GRAY, TableCell.STRING, null);
		table.add(new TableRow(header));
		FavoriteService service = new FavoriteService(StationListActivity.this);
		List<Favirote> list = service.findFaviroteList();
		for (int i = 0; i < list.size(); i++) {
			Favirote favirote = list.get(i);
			TableCell[] cells = new TableCell[cols];
			String type = favirote.getType();
			String locationtype = CommConstant.STATIONTYPE_MAP.get(type);
			cells[0] = new TableCell(locationtype + " ■ " + favirote.getName() + "@" + favirote.getAddr(), width[0],itemHeight, color, TableCell.DEFINE,new TextItemOnClickListener(favirote));
			cells[1] = new TableCell(R.drawable.expand, width[1], itemHeight, color, TableCell.IMAGE, new ImageItemOnClickListener(favirote));
			table.add(new TableRow(cells));
		}
		NormalTableAdapter tableAdapter = new NormalTableAdapter(this, table);
		ListView lstWaterStation = (ListView) findViewById(R.id.lstStationList);
		lstWaterStation.setAdapter(tableAdapter);
	}
	
	private class TextItemOnClickListener implements OnClickListener {
		private Favirote favirote;

		public TextItemOnClickListener(Favirote favirote) {
			this.favirote = favirote;
		}
		
		public TextItemOnClickListener() {
			
		}

		public void onClick(View v) {
			Intent intent = new Intent();
			intent.putExtra("code", favirote.getCode());
			intent.putExtra("name", favirote.getName());
			int type = Integer.parseInt(favirote.getType());
			switch(type){
				case CommConstant.Station.RAIN_LOCATION:
					intent.setClass(getApplicationContext(),RainStationDetailActivity.class);
					break;
				case CommConstant.Station.WATER_LOCATION:
					intent.setClass(getApplicationContext(),WaterStationDetailActivity.class);
					break;
				case CommConstant.Station.SOIL_LOCATION:
					intent.setClass(getApplicationContext(),SoilStationDetailActivity.class);
					break;
				case CommConstant.Station.SALT_LOCATION:
					intent.setClass(getApplicationContext(),SaltStationDetailActivity.class);
					break;
			}			
			startActivity(intent);
		}

	}
	
	private class ImageItemOnClickListener implements OnClickListener {
		private Favirote favirote;

		public ImageItemOnClickListener(Favirote favirote) {
			this.favirote = favirote;
		}

		public void onClick(View v) {
			Builder builder = new AlertDialog.Builder(StationListActivity.this);
			builder.setTitle("测站删除")
			.setMessage("是否确定要删除此测站").setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface,int i) {
							FavoriteService service = new FavoriteService(StationListActivity.this);
							service.delete(favirote.getCode());
							fillStationList();
						}
					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface,int i) {
							
						}
					}).show();
		}
	}

	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_SEARCH, 1, R.string.menu_location_search);
		menu.add(0, MENU_DOWNLOAD, 1, R.string.menu_download);
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = new Intent();
		switch (item.getItemId()) {
			case MENU_SEARCH:
				intent.setClass(getApplicationContext(),StationSearchActivity.class);
				startActivity(intent);
				return true;
			case MENU_DOWNLOAD:
				dialog = new ProgressDialog(this);
				dialog.setTitle("测站列表");
				dialog.setMessage("数据下载中,请稍候...");
				dialog.show();
				final Handler hanlder = new Handler(){
					public void handleMessage(Message msg)	{
						if (msg.what == 1)	{
						}
					}
				};
				
				new Thread(){
					public void run(){
						Looper.prepare();
						downloadStationList();
						Message m = new Message();
						m.what = 1;
						hanlder.sendMessage(m);
						Looper.loop();
					};

				}.start();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onDestroy() {
		super.onDestroy();
		service.closeDB();
        ActivityStackControlUtil.remove(this);
	}
}